package io.aicn.lowcode.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/db")
public class DatabaseInitController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @PostMapping("/init")
    public String initDatabase() {
        try {
            int executedCount = 0;
            int errorCount = 0;
            StringBuilder result = new StringBuilder();
            
            // 先删除现有表
            String[] dropTableSqls = {
                "DROP TABLE IF EXISTS `dbm_datasource`",
                "DROP TABLE IF EXISTS `dbm_data_dictionary`"
            };
            
            for (String sql : dropTableSqls) {
                try {
                    jdbcTemplate.execute(sql);
                    executedCount++;
                    result.append("成功删除现有表\\n");
                } catch (Exception e) {
                    errorCount++;
                    result.append("删除表失败: ").append(e.getMessage()).append("\\n");
                }
            }
            
            // 直接执行建表SQL
            String[] createTableSqls = {
                // 数据源配置表
                "CREATE TABLE `dbm_datasource` (" +
                "`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID'," +
                "`name` varchar(100) NOT NULL COMMENT '数据源名称'," +
                "`type` varchar(20) NOT NULL COMMENT '数据库类型(mysql/postgresql)'," +
                "`host` varchar(255) NOT NULL COMMENT '主机地址'," +
                "`port` int NOT NULL COMMENT '端口号'," +
                "`database_name` varchar(64) NOT NULL COMMENT '数据库名'," +
                "`username` varchar(64) NOT NULL COMMENT '用户名'," +
                "`password` varchar(255) NOT NULL COMMENT '密码(加密)'," +
                "`status` varchar(20) DEFAULT 'disconnected' COMMENT '连接状态'," +
                "`config` json COMMENT '扩展配置'," +
                "`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'," +
                "`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'," +
                "`create_by` varchar(64) COMMENT '创建人'," +
                "`update_by` varchar(64) COMMENT '更新人'," +
                "PRIMARY KEY (`id`)," +
                "UNIQUE KEY `uk_name` (`name`)," +
                "KEY `idx_type` (`type`)," +
                "KEY `idx_status` (`status`)" +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='数据源配置表'",
                
                // 数据字典表
                "CREATE TABLE `dbm_data_dictionary` (" +
                "`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID'," +
                "`dict_type` varchar(100) NOT NULL COMMENT '字典类型'," +
                "`dict_code` varchar(100) NOT NULL COMMENT '字典编码'," +
                "`dict_label` varchar(100) NOT NULL COMMENT '字典标签'," +
                "`dict_value` varchar(100) NOT NULL COMMENT '字典键值'," +
                "`css_class` varchar(100) DEFAULT NULL COMMENT '样式属性'," +
                "`list_class` varchar(100) DEFAULT NULL COMMENT '表格回显样式'," +
                "`is_default` char(1) DEFAULT 'N' COMMENT '是否默认(Y是 N否)'," +
                "`is_enabled` tinyint(1) DEFAULT 1 COMMENT '是否启用(1启用 0禁用)'," +
                "`status` char(1) DEFAULT '0' COMMENT '状态(0正常 1停用)'," +
                "`create_by` varchar(64) DEFAULT '' COMMENT '创建者'," +
                "`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'," +
                "`update_by` varchar(64) DEFAULT '' COMMENT '更新者'," +
                "`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'," +
                "`remark` varchar(500) DEFAULT NULL COMMENT '备注'," +
                "`sort_order` int DEFAULT '0' COMMENT '排序'," +
                "PRIMARY KEY (`id`)," +
                "UNIQUE KEY `uk_dict_type_code` (`dict_type`,`dict_code`)," +
                "KEY `idx_dict_type` (`dict_type`)," +
                "KEY `idx_status` (`status`)" +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='数据字典表'"
            };
            
            for (String sql : createTableSqls) {
                try {
                    jdbcTemplate.execute(sql);
                    executedCount++;
                    result.append("成功执行建表SQL\\n");
                } catch (Exception e) {
                    errorCount++;
                    result.append("执行SQL失败: ").append(e.getMessage()).append("\\n");
                }
            }
            
            // 插入初始数据
            String[] insertSqls = {
                "INSERT IGNORE INTO `dbm_data_dictionary` (`dict_type`, `dict_code`, `dict_label`, `dict_value`, `status`, `create_time`, `sort_order`) VALUES " +
                "('data_type', 'varchar', 'VARCHAR', 'varchar', '0', NOW(), 1)," +
                "('data_type', 'int', 'INT', 'int', '0', NOW(), 2)," +
                "('data_type', 'bigint', 'BIGINT', 'bigint', '0', NOW(), 3)," +
                "('data_type', 'decimal', 'DECIMAL', 'decimal', '0', NOW(), 4)," +
                "('data_type', 'datetime', 'DATETIME', 'datetime', '0', NOW(), 5)"
            };
            
            for (String sql : insertSqls) {
                try {
                    jdbcTemplate.execute(sql);
                    executedCount++;
                    result.append("成功插入初始数据\\n");
                } catch (Exception e) {
                    errorCount++;
                    result.append("插入数据失败: ").append(e.getMessage()).append("\\n");
                }
            }
            
            return "数据库初始化完成，执行了 " + executedCount + " 条SQL语句，错误 " + errorCount + " 个\\n" + result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "数据库初始化失败: " + e.getMessage();
        }
    }
}